package com.fanqj.resilience4j.controller;

import com.fanqj.resilience4j.service.ITestService;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 限时
 * @author <a href="mailto:fanqijin@wxchina.com">fanqj</a>
 * @Date 2021年01月27日 11:45
 * @Version 6.4.1
 */
public class TimeLimitController {
    private TimeLimiter timeLimiter;
    @Autowired
    private ITestService iTestService;

    public TimeLimitController() throws Exception {
    }

    @PostConstruct
    private void init(){
        TimeLimiterConfig config = TimeLimiterConfig.custom()
                //超时时是否中断异步执行的方法
                .cancelRunningFuture(true)
                //超时时间
                .timeoutDuration(Duration.ofMillis(500))
                .build();
        timeLimiter = TimeLimiter.of("TimeLimiter-A", config);
    }

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

    // 返回CompletableFuture类型的非阻塞变量
    CompletableFuture<String> result = timeLimiter.executeCompletionStage(
            scheduler, () -> CompletableFuture.supplyAsync(() -> iTestService.testTimeLimit(600))).toCompletableFuture();

    // 阻塞方式，实际上是调用了future.get(timeoutDuration, MILLISECONDS)
    String result1 = timeLimiter.executeFutureSupplier(
            () -> CompletableFuture.supplyAsync(() -> iTestService.testTimeLimit(600)));

}
